package net.cyue.wj.user;


import jakarta.validation.Valid;
import net.cyue.nest.nestjava.common.annotation.core.Controller;
import net.cyue.nest.nestjava.common.annotation.http.Body;
import net.cyue.nest.nestjava.common.annotation.http.PostMethod;
import net.cyue.nest.nestjava.common.annotation.http.Response;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPResponse;
import net.cyue.nest.nestjava.common.util.JSONUtil;
import net.cyue.web.WebResult;
import net.cyue.wj.user.dto.UserLoginDTO;
import net.cyue.wj.user.dto.UserRegisterDTO;
import net.cyue.wj.user.entity.User;
import net.cyue.jpa.JPAUtil;
import net.cyue.util.JWTUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller("/user")
public class UserController {

    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24;
    private static final Map<Integer, String> TOKEN_CACHE_MAP = new HashMap<>();

    @PostMethod
    public void register(
        @Response IHTTPResponse response,
        @Valid @Body UserRegisterDTO userRegisterDTO
    ) {
        Integer uid = (Integer) JPAUtil.selectOne(
        "select u.id from User u where u.username = ?1",
           userRegisterDTO.getUsername()
        );
        if (uid != null) {
            response.send(WebResult.failed("用户名已被使用"));
            return;
        }

        User user = userRegisterDTO.toUser();
        System.out.println(JSONUtil.toJSONString(user));
        JPAUtil.persist(user);
        response.send(WebResult.success("注册成功"));
    }

    @PostMethod("/login")
    public void login(
        @Response IHTTPResponse response,
        @Valid @Body UserLoginDTO userLoginDTO
    ) {
        User user = userLoginDTO.toUser();
        user = (User) JPAUtil.selectOne(
            "select u from User u where u.username = ?1 and u.password = ?2",
            user.getUsername(),
            user.getPassword()
        );
        if (user == null) {
            response.send(WebResult.failed("用户名或密码错误"));
            return;
        }

        String token = TOKEN_CACHE_MAP.get(user.getId());
        if (token != null && JWTUtil.verify(token, user.getPassword())) {
            response.send(WebResult.success("登录成功", token));
            return;
        }

        token = JWTUtil.generateJWT(
            user.getPassword(),
            Map.of(
                "id",
                user.getId(),
                "username",
                user.getUsername()
            ),
            new Date(System.currentTimeMillis() + EXPIRATION_TIME)
        );
        TOKEN_CACHE_MAP.put(user.getId(), token);
        response.send(WebResult.success("登录成功", token));
    }
}

